﻿#include <string.h>
#include "senddatabuffer.h"

SendDataBuffer& SendDataBuffer::getInstance()
{
    static SendDataBuffer s_sendDataBuffer;
    return s_sendDataBuffer;
}

//
SendDataBuffer::SendDataBuffer()
{
    for (int i = 0; i < CHANNAL_COUNT; i++)
	{
        memset(m_sendBuffer, 0, sizeof(m_sendBuffer));
        for (int j = 0; j < DATA_COUNT; j++)
		{
            m_sendBuffer[i][j].channelId = i ;
            m_sendBuffer[i][j].dataLen = 0 ;
		}
        m_readIndex[i] = 0;
        m_writeIndex[i] = 0;
	}
}

/**
 * @brief ReciveDataBuffer::writeDataToBuffer   将数据后写入buffer
 * @param index     索引
 * @param buf       数据地址
 * @param len       数据长度
 * @return          写入状态，true=成功，false=失败
 */
bool SendDataBuffer::writeDataToBuffer(int serverIndex, unsigned char *buf, int len)
{
    if(buf == NULL || len <=0 || len > BUFFER_SIZE)
	{
		return false;
	}
	
    std::unique_lock<std::mutex> lock(m_mutex);

    DATABUFFER sendData ;
    memset(&sendData, 0, sizeof(sendData)) ;

    sendData.channelId = serverIndex ;
	sendData.dataLen = len ;
	memcpy(sendData.dataBuf, buf, len);
	
    m_sendBuffer[serverIndex][m_writeIndex[serverIndex]] = sendData ;
		
    m_writeIndex[serverIndex] = (m_writeIndex[serverIndex] + 1) % DATA_COUNT;
    if(m_writeIndex[serverIndex] == m_readIndex[serverIndex])
    {
        m_readIndex[serverIndex] = (m_readIndex[serverIndex] + 1) % DATA_COUNT;
    }
	
	return true;
}

/**
 * @brief ReciveDataBuffer::readDataFromBuffer  从buffer中读数据
 * @param index             索引
 * @param buf               数据地址
 * @param bufLength         预读数据长度
 * @param getLength         实际读取长度
 * @return                  读取状态，true=成功，false=失败
 */
bool SendDataBuffer::readDataFromBuffer(int serverIndex, char *buf, int bufLength ,int &getLength)
{
    if (buf == NULL || bufLength <= 0)
	{
		return false;
	}
	
    std::unique_lock<std::mutex> lock(m_mutex);

    // 如果当前读取的数据包，已经到了之前送入的数据包的最后一个，即新的数据都读取完毕了
    if(m_readIndex[serverIndex] == m_writeIndex[serverIndex])
    {
        return false;
	}
	
    memcpy(buf, m_sendBuffer[serverIndex][m_readIndex[serverIndex]].dataBuf,
        m_sendBuffer[serverIndex][m_readIndex[serverIndex]].dataLen);
		
    getLength = m_sendBuffer[serverIndex][m_readIndex[serverIndex]].dataLen ;
	
    m_readIndex[serverIndex] = (m_readIndex[serverIndex] + 1) % DATA_COUNT;

	return true;
}
